package com.hiultra.archive.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hiultra.archive.domain.ArcBox;
import com.hiultra.archive.domain.ArchiveBoxMove;
import com.hiultra.archive.domain.ArchiveBoxMoveTask;
import com.hiultra.archive.domain.vo.ArchiveBoxMoveTaskIssuedVo;
import com.hiultra.archive.domain.vo.ArchiveBoxMoveTaskReportVo;
import com.hiultra.archive.domain.vo.ArchiveDesTaskIssuedVo;
import com.hiultra.archive.domain.vo.ResultEntity;
import com.hiultra.archive.mapper.ArcBoxMapper;
import com.hiultra.archive.mapper.ArchiveBoxMoveMapper;
import com.hiultra.archive.mapper.ArchiveBoxMoveTaskMapper;
import com.hiultra.archive.service.IArchiveBoxMoveService;
import com.hiultra.archive.service.IArchiveBoxMoveTaskService;
import com.hiultra.archive.utils.sgsm.SM2Util;
import com.hiultra.archive.utils.tool.ToolUtils;
import com.hiultra.common.constant.BusinessConstants;
import com.hiultra.common.exception.ServiceException;
import com.hiultra.common.utils.DateUtils;
import com.hiultra.common.utils.uuid.UUID;
import jdk.nashorn.internal.runtime.ListAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

/**
 * 盒移位任务Service业务层处理
 *
 * @author 派大星
 * @date 2024-07-23
 */
@Service
public class ArchiveBoxMoveTaskServiceImpl implements IArchiveBoxMoveTaskService {
    private static final Logger log = LoggerFactory.getLogger(ArchiveBoxMoveTaskServiceImpl.class);

    @Autowired
    private ArchiveBoxMoveTaskMapper archiveBoxMoveTaskMapper;
    @Autowired
    private IArchiveBoxMoveService archiveBoxMoveService;
    @Autowired
    private ArcBoxMapper arcBoxMapper;

    @Value("${priKey}")
    private String priKey;

    /**
     * 查询盒移位任务
     *
     * @param taskId 盒移位任务主键
     * @return 盒移位任务
     */
    @Override
    public ArchiveBoxMoveTask selectArchiveBoxMoveTaskByTaskId(String taskId) {
        return archiveBoxMoveTaskMapper.selectArchiveBoxMoveTaskByTaskId(taskId);
    }

    /**
     * 查询盒移位任务列表
     *
     * @param archiveBoxMoveTask 盒移位任务
     * @return 盒移位任务
     */
    @Override
    public List<ArchiveBoxMoveTask> selectArchiveBoxMoveTaskList(ArchiveBoxMoveTask archiveBoxMoveTask) {
        return archiveBoxMoveTaskMapper.selectArchiveBoxMoveTaskList(archiveBoxMoveTask);
    }

    /**
     * 新增盒移位任务
     *
     * @param archiveBoxMoveTask 盒移位任务
     * @return 结果
     */
    @Override
    public int insertArchiveBoxMoveTask(ArchiveBoxMoveTask archiveBoxMoveTask) {
        archiveBoxMoveTask.setCreateTime(DateUtils.getNowDate());
        return archiveBoxMoveTaskMapper.insertArchiveBoxMoveTask(archiveBoxMoveTask);
    }

    /**
     * 修改盒移位任务
     *
     * @param archiveBoxMoveTask 盒移位任务
     * @return 结果
     */
    @Override
    public int updateArchiveBoxMoveTask(ArchiveBoxMoveTask archiveBoxMoveTask) {
        return archiveBoxMoveTaskMapper.updateArchiveBoxMoveTask(archiveBoxMoveTask);
    }

    /**
     * 批量删除盒移位任务
     *
     * @param taskIds 需要删除的盒移位任务主键
     * @return 结果
     */
    @Override
    public int deleteArchiveBoxMoveTaskByTaskIds(String[] taskIds) {
        return archiveBoxMoveTaskMapper.deleteArchiveBoxMoveTaskByTaskIds(taskIds);
    }

    /**
     * 删除盒移位任务信息
     *
     * @param taskId 盒移位任务主键
     * @return 结果
     */
    @Override
    public int deleteArchiveBoxMoveTaskByTaskId(String taskId) {
        return archiveBoxMoveTaskMapper.deleteArchiveBoxMoveTaskByTaskId(taskId);
    }

    /**
     * 档案盒移位任务下发接口
     *
     * @param data
     * @return 结果
     */
    @Override
    public ResultEntity insertIssuedArchiveBoxMoveTask(String data) throws ParseException {
        //解密
        System.out.println("档案盒移位任务下发据：" + data);
        String decryptedResult = new SM2Util().decryptBySM2(data, priKey);
        System.out.println("档案盒移位任务下发解密结果：" + decryptedResult);
        ArchiveBoxMoveTaskIssuedVo archiveBoxMoveTaskIssuedVo = JSON.parseObject(decryptedResult.trim(), ArchiveBoxMoveTaskIssuedVo.class);

        if (ObjectUtil.isNull(archiveBoxMoveTaskIssuedVo)) {
            // 返回错误信息或抛出异常
            log.info("入参解析出错，请检查重试");
            return ResultEntity.error("入参解析出错，请检查重试");
        }
        try {
            processArchiveBoxMoveTask(archiveBoxMoveTaskIssuedVo);
        } catch (ServiceException e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
        return ResultEntity.success();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void processArchiveBoxMoveTask(ArchiveBoxMoveTaskIssuedVo archiveBoxMoveTaskIssuedVo) throws ServiceException {
        try {
            if (ObjectUtil.isNotNull(archiveBoxMoveTaskIssuedVo)) {
                ArchiveBoxMoveTask archiveBoxMoveTask = ToolUtils.convertEntity(archiveBoxMoveTaskIssuedVo, ArchiveBoxMoveTask::new);
                //如果不存在才新增到数据库
                ArchiveBoxMoveTask archiveBoxMoveTask1 = selectArchiveBoxMoveTaskByTaskId(archiveBoxMoveTask.getTaskId());
                if (null == archiveBoxMoveTask1) {
                    archiveBoxMoveTask.setTaskId(UUID.randomUUID().toString().replace("-", ""));
                    archiveBoxMoveTask.setBoxMoveStatus(BusinessConstants.BOX_MOVE_STATUS);

                    insertArchiveBoxMoveTask(archiveBoxMoveTask);
                    for (ArchiveBoxMoveTaskIssuedVo.BoxMoveInfo boxMoveInfo : archiveBoxMoveTaskIssuedVo.getBoxMoveList()) {
                        ArchiveBoxMove archiveBoxMove = ToolUtils.convertEntity(boxMoveInfo, ArchiveBoxMove::new);
                        archiveBoxMove.setId(UUID.randomUUID().toString().replace("-", ""));
                        //根据盒id查询盒信息
                        ArcBox archiveBox = arcBoxMapper.selectArcBoxByBoxId(boxMoveInfo.getBoxId());
                        if (ObjectUtil.isEmpty(archiveBox)) {
                            log.info("档案盒标识" + archiveBox.getBoxId() + "不存在,请检查重试");
                            throw new ServiceException("档案盒标识" + archiveBox.getBoxId() + "不存在，请检查后重试！");
                        }
                        archiveBoxMove.setBoxNo(archiveBox.getBoxCode());
                        archiveBoxMove.setTaskId(archiveBoxMoveTask.getTaskId());
                        archiveBoxMove.setBoxMoveStatus(BusinessConstants.BOX_MOVE_STATUS);
                        archiveBoxMoveService.insertArchiveBoxMove(archiveBoxMove);
                    }
                }
            }
        } catch (ServiceException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ServiceException(e.getMessage());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ServiceException("发生未知异常，事务已回滚");
        }
    }

}
